package com.li.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.li.entity.PageResult;
import com.li.entity.QueryPageBean;
import com.li.mapper.SetMealMapper;
import com.li.pojo.Setmeal;
import com.li.service.SetmealService;
import com.li.utils.QiniuUtils;
import com.li.utils.RedisConstant;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    SetMealMapper setMealMapper;
    @Autowired
    JedisPool jedisPool;
    @Autowired
    FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${target_path}")
    String targetDir;
    /*
    新增检查套餐
     */
    public void add(Setmeal setmeal, Integer[] ids) {

        //新增检查套餐
        setMealMapper.add(setmeal);
        //定义检查套餐与检查组之间的关联
        this.addSetmealAndCheckGroup(setmeal.getId(),ids);
        //向redis缓存插入数据
        jedisPool.getResource().sadd(RedisConstant.getSetmealPicDbResources(),setmeal.getImg());

        //新增套餐之后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    //用于生成静态页面
    @PostConstruct
    public void generateMobileStaticHtml(){
        //获取模板所需要的数据
        List<Setmeal> setmealList = this.getAll();
        //生成列表页面
        generateMobileSetmealListHtml(setmealList);
        //生成详情页面
        generateMobileSetmealDetailHtml(setmealList);
    }
    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list){

        HashMap<String, Object> map = new HashMap<>();
        map.put("setmealList",list);
        this.generateStaticPage("setmeal.ftl","setmeal.html",map);
    }
    //生成套餐详情静态页面
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){

        for (Setmeal setmeal : list) {
            HashMap<String, Object> map = new HashMap<>();

            map.put("setmeal",this.findSetmealById(setmeal.getId()));
            this.generateStaticPage("setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }

    }
    /*
    用于生成静态页面 通用 模板名字,模板数据,html页面名
     */
    public void generateStaticPage(String templateName, String htmlPageName, Map<String,Object> dataMap){

            //获取配置类
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out=null;
        try{
            //加载模板文件
            Template template = configuration.getTemplate(templateName);
            //生成数据
            File file = new File(targetDir + "/" + htmlPageName);
            out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"utf-8"));
            template.process(dataMap,out);
        }catch (Exception e){

        }finally {

            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void addSetmealAndCheckGroup(Integer setmealId, Integer[] checkGroupId) {

        if(checkGroupId!=null&&checkGroupId.length>0){
            //有关联 进行关联
            //遍历ids
            for (Integer id : checkGroupId) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("setmealId",setmealId);
                map.put("checkGroupId",id);
                //进行关联
                setMealMapper.addSetmealAndCheckGroup(map);
            }
        }
    }

    @Override
    public List<Setmeal> getAll() {

        return setMealMapper.getAll();
    }

    @Override
    public Setmeal findSetmealById(Integer id) {

        return setMealMapper.findById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmelCount() {

        //查询套餐数据 name:"套餐名" value:"套餐数量"
        return setMealMapper.findSetmealCount();
    }

    @Override
    public List<Setmeal> getAllHot() {
        return setMealMapper.getAllHot();
    }

    @Override
    public List<Setmeal> getAllUpdate() {
        return setMealMapper.getAllUpdate();
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> pageByCondition = setMealMapper.findPageByCondition(queryString);

        PageResult result = new PageResult();
        result.setRows(pageByCondition.getResult());
        result.setTotal(pageByCondition.getTotal());

        return result;
    }


    // 删除 编辑
    // 修改套餐组数据
    public void update(Setmeal setmeal, Integer[] checkgroupIds) {

        // 先保存setmeal
        setMealMapper.updateById(setmeal);
        System.out.println(setmeal);
        // 保存 关系
        // 先删除
        setMealMapper.deleteCheckGroupIdAndSetMealId(setmeal.getId());
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            // 添加套餐与检查组信息
            this.setMealsIdAndCheckGroupIds(checkgroupIds, setmeal.getId());
        }
        // 存入缓冲
        jedisPool.getResource().sadd(RedisConstant.getSetmealPicDbResources(), setmeal.getImg());

        // 更新静态页面
        generateMobileStaticHtml();
    }

    // 回显
    public Setmeal findSetmeal(int id) {

        Setmeal setmeal = setMealMapper.findSetmealsById(id);
        System.out.println(setmeal);

        return setmeal;
    }


    public Integer[] findCheckGroupsIdsById(int id) {
        Integer[] checkgroupIds = setMealMapper.findCheckGroupsIdsById(id);
        return checkgroupIds;
    }

    // 根据id删除
    public void deleteById(int id) {



        // 1 先删除检查组与套餐间对应关系
        setMealMapper.deleteCheckGroupIdAndSetMealId(id);
        // 2 先获取图片名称 再删除
        Setmeal setmeal = setMealMapper.findSetmealsById(id);
        deleteByImgInRedis(setmeal.getImg());
        // 3 在删除套餐
        setMealMapper.deleteMeal(id);

        // 更新静态页面
        generateMobileStaticHtml();
    }

    // 删除对应数据库缓冲中以及的图片字符串
    public void deleteByImgInRedis(String img) {
        // 删除数据库缓冲中的对应图片
        jedisPool.getResource().srem(RedisConstant.getSetmealPicDbResources(), img);
        // 删除七牛云缓冲中的对应图片
        jedisPool.getResource().srem(RedisConstant.getSetmealPicResources(), img);
        // 删除七牛云中的对应图片
        QiniuUtils.deleteFileFromQiniu(img);

    }

    //保存中间表关联关系存在
    public void setMealsIdAndCheckGroupIds(Integer[] checkgroupIds, int setmealId) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkGroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<String, Integer>();
                map.put("checkgroup_id", checkGroupId);
                map.put("setmeal_id", setmealId);
                setMealMapper.addMealsIdAndCheckGroupIds(map);
            }

        }
    }
    //根据搜索条件模糊查询
    public List<Setmeal> findByCondition(String queryString){
        return setMealMapper.findByCondition(queryString);
    }

}
